import { USER_ACTION_TYPES } from "../actionTypes";
import { api } from "@/api/api";
import {setShopId} from "./shopActions";

// 登录开始
export const loginStart = () => ({
  type: USER_ACTION_TYPES.LOGIN_START,
});

// 登录成功
export const loginSuccess = (userInfo, token) => ({
  type: USER_ACTION_TYPES.LOGIN_SUCCESS,
  payload: { userInfo, token },
});

// 登录失败
export const loginFailure = (error) => ({
  type: USER_ACTION_TYPES.LOGIN_FAILURE,
  payload: error,
});

// 退出登录
export const logout = () => ({
  type: USER_ACTION_TYPES.LOGOUT,
});

// 更新用户信息
export const updateUserInfo = (userInfo) => ({
  type: USER_ACTION_TYPES.UPDATE_USER_INFO,
  payload: userInfo,
});

// 清除错误
export const clearError = () => ({
  type: USER_ACTION_TYPES.CLEAR_ERROR,
});

// 微信授权登录
export const wechatLogin = (code,shopId) => {
  return async (dispatch, getState) => {
    dispatch(loginStart());
    try {
      const tokenResponse = await api.getToken({ code, shopId });

      if (tokenResponse.code !== 200) {
        throw new Error(tokenResponse.msg || "获取token失败");
      }

      const tokenData = tokenResponse.data;
      let token, appId;
      
      if (typeof tokenData === 'object' && tokenData.token) {
        token = tokenData.token;
        appId = tokenData.appid;
        localStorage.setItem("wechat_token", token);
        localStorage.setItem("wechat_appid", appId);
      } else {
        token = tokenData;
        localStorage.setItem("wechat_token", token);
      }
      localStorage.setItem("shop_id", shopId);

      const loginResponse = await api.wxLogin({ shopId });

      if (loginResponse.code === 200) {
        const userInfo = loginResponse.data;
        localStorage.setItem("user_info", JSON.stringify(userInfo));
        

        dispatch(loginSuccess(userInfo, token));
        dispatch(setShopId(shopId));

        return { success: true, userInfo, token, shopId };
      } else {
        throw new Error(loginResponse.message || "登录失败");
      }
    } catch (error) {
      console.error("微信登录失败:", error);
      dispatch(loginFailure(error.message || "登录失败"));
      return { success: false, error: error.message };
    }
  };
};

// 检查登录状态
export const checkLoginStatus = () => {
  return async (dispatch) => {
    try {
      const token = localStorage.getItem("wechat_token");
      const shopId = localStorage.getItem("shop_id");

      if (!token) {
        return false;
      }
      const loginResponse = await api.wxLogin({shopId});

      if (loginResponse.code === 200) {
        const userInfo = loginResponse.data;
        dispatch(loginSuccess(userInfo, token));
        dispatch(setShopId(shopId));
        return true;
      } else {
        // token无效，清除本地存储
        localStorage.removeItem("wechat_token");
        localStorage.removeItem("wechat_appid");
        localStorage.removeItem("user_info");
        localStorage.removeItem("shop_id");
        dispatch(logout());
        return false;
      }
    } catch (error) {
      console.error("检查登录状态失败:", error);
      // 清除所有相关缓存数据
      localStorage.removeItem("wechat_token");
      localStorage.removeItem("wechat_appid");
      localStorage.removeItem("user_info");
      localStorage.removeItem("shop_id");
      dispatch(logout());
      return false;
    }
  };
};

// 退出登录
export const logoutUser = () => {
  return (dispatch) => {
    // 清除所有相关缓存数据
    localStorage.removeItem("wechat_token");
    localStorage.removeItem("wechat_appid");
    localStorage.removeItem("user_info");
    localStorage.removeItem("shop_id");
    dispatch(logout());
  };
};
